import 'dart:convert';

import 'package:dio/dio.dart';
/**
 * 我的银行卡页面
 * author wim
 */
import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_easyrefresh/material_footer.dart';
import 'package:flutter_easyrefresh/material_header.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:fluttertoast/fluttertoast.dart';
import '../../entity/user_bank_entity.dart';
import '../../http/Api.dart';
import '../../http/HttpUtil.dart';
import '../../util/AppSaveInfoUtil.dart';
import '../../util/LoadingUtil.dart';
import '../../util/SignUtil.dart';
import '../../base/Constant.dart';
import './AddBank.dart';

class MyBankPage extends StatefulWidget {
  MyBankPage({Key key}) : super(key: key);

  @override
  _MyBankPageState createState() => _MyBankPageState();
}

class _MyBankPageState extends State<MyBankPage> {
  EasyRefreshController _controller = EasyRefreshController();
  List<UserBankListDataData> dataList = new List();
  String token = "";
  int page = 1;

  @override
  void initState() {
    super.initState();
    getString(TOKEN).then((value) {
      token = value;
      loadList();
    });
  }

  loadList() async {
    Map map = new Map();
    map['token'] = token;
    map['p'] = page.toString();
    map['per'] = "10";
    map['sign_type'] = createSignType(Api.URL_BANKCARD_LIST);
    Response<String> response =
        await HttpUtil().post(Api.URL_BANKCARD_LIST, data: getSign(map));
    Map userMap = json.decode(response.data);
    if (userMap['code'] != 1) {
      Fluttertoast.showToast(msg: userMap['msg']);
      return;
    }
    UserBankListEntity homeListEntity =
        new UserBankListEntity.fromJson(userMap);
    if (mounted)
      setState(() {
        if (page == 1) {
          dataList.clear();
          dataList.addAll(homeListEntity.data.datas);
          _controller.finishRefresh();
          _controller.resetLoadState();
        } else {
          dataList.addAll(homeListEntity.data.datas);
          _controller.finishLoad(noMore: homeListEntity.data.datas.length == 0);
        }
      });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: new AppBar(
        title: new Text(
          "我的银行卡",
          style: TextStyle(
              fontSize: ScreenUtil.getInstance().setSp(BIG_FONT_SIZE),
              color: Colors.black),
        ),
        elevation: 0.5,
        backgroundColor: Colors.white,
        brightness: Brightness.light,
        centerTitle: true,
        iconTheme: new IconThemeData(color: Colors.black),
      ),
      body: Container(
        child: new Column(
          children: <Widget>[
            Expanded(
              child: new EasyRefresh(
                enableControlFinishRefresh: true,
                enableControlFinishLoad: true,
                header: MaterialHeader(),
                footer: MaterialFooter(),
                controller: _controller,
                child: ListView.separated(
                    itemBuilder: _renderRow,
                    separatorBuilder: (BuildContext context, int index) {
                      return Container(
                        color: divideColor,
                        height: 1,
                      );
                    },
                    itemCount: dataList.length),
                onRefresh: () async {
                  page = 1;
                  loadList();
                },
                onLoad: () async {
                  page++;
                  loadList();
                },
              ),
            ),
            new Container(
              width: double.infinity,
              height: ScreenUtil.getInstance().setHeight(DP_80),
              margin: EdgeInsets.all(ScreenUtil.getInstance().setHeight(DP_80)),
              decoration: new BoxDecoration(
                  border: Border.all(color: mainColor, width: 1),
                  borderRadius: BorderRadius.circular(5)),
              padding: EdgeInsets.fromLTRB(0.0, 0.0, 0.0, 0.0),
              child: new FlatButton(
                child: new Padding(
                  padding: EdgeInsets.all(0.0),
                  child: new Text(
                    "+  添加银行卡",
                    style: new TextStyle(
                        color: mainColor,
                        fontSize:
                            ScreenUtil.getInstance().setSp(NORMAL_FONT_SIZE)),
                  ),
                ),
                onPressed: () {
                  Navigator.of(context)
                      .push<String>(new MaterialPageRoute(builder: (context) {
                    return new AddBankPage();
                  })).then((value) {
                    if (value != null) {
                      page = 1;
                      loadList();
                    }
                  });
                },
              ),
            )
          ],
        ),
      ),
    );
  }

  Widget _renderRow(BuildContext context, int index) {
    return new GestureDetector(
      child: Container(
        color: white,
        padding: EdgeInsets.fromLTRB(
            ScreenUtil.getInstance().setHeight(DP_10),
            ScreenUtil.getInstance().setHeight(DP_10),
            ScreenUtil.getInstance().setHeight(DP_10),
            ScreenUtil.getInstance().setHeight(DP_10)),
        child: Row(
          children: <Widget>[
            Image.network(
              Api.BaseUrl + dataList[index].icon,
              scale: 2.2,
            ),
            Container(
              width: 10,
            ),
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisAlignment: MainAxisAlignment.start,
                children: <Widget>[
                  Text(
                    dataList[index].bank_name,
                    style: TextStyle(
                        color: black,
                        fontSize:
                            ScreenUtil.getInstance().setSp(BIG_FONT_SIZE)),
                  ),
                  Container(
                    height: 5,
                  ),
                  Text(
                    dataList[index].truename +
                        "(" +
                        dataList[index].account +
                        ")",
                    style: TextStyle(
                        color: black_99,
                        fontSize:
                            ScreenUtil.getInstance().setSp(NORMAL_FONT_SIZE)),
                  ),
                ],
              ),
            ),
            Column(
              crossAxisAlignment: CrossAxisAlignment.end,
              mainAxisAlignment: MainAxisAlignment.end,
              children: <Widget>[
                GestureDetector(
                  behavior: HitTestBehavior.opaque,
                  onTap: () {
                    deleteAddress(context, index);
                  },
                  child: Text(
                    '删除',
                    style: TextStyle(
                        color: Colors.black54,
                        fontSize:
                            ScreenUtil.getInstance().setSp(NORMAL_FONT_SIZE)),
                  ),
                )
              ],
            ),
            Container(
              width: 10,
            ),
          ],
        ),
      ),
      onTap: () {
        // if (widget.type == 1) {
        //   Navigator.of(context).pop(dataList[index]);
        // }
      },
    );
  }

  deleteAddress(BuildContext context, int index) {
    showDialog(
      context: context,
      builder: (context) => new AlertDialog(
        title: new Text('提示'),
        content: new Text('确定删除该银行卡号码，删除后不可撤回'),
        actions: <Widget>[
          new FlatButton(
            onPressed: () => Navigator.of(context).pop(false),
            child: new Text(
              '取消',
              style: TextStyle(color: Colors.grey),
            ),
          ),
          new FlatButton(
            onPressed: () {
              del(index);
              Navigator.of(context).pop(false);
            },
            child: new Text('确定删除', style: TextStyle(color: mainColor)),
          ),
        ],
      ),
    );
  }

  del(int index) async {
    Map map = new Map();
    map['token'] = token;
    map['id'] = dataList[index].id;
    map['sign_type'] = createSignType(Api.URL_BANKCARD_DEL);
    print(map);
    Response<String> response =
        await HttpUtil().post(Api.URL_BANKCARD_DEL, data: getSign(map));
    Map userMap = json.decode(response.data);
    int code = userMap["code"];
    String msg = userMap["msg"];
    Fluttertoast.showToast(msg: msg);
    // print(userMap['data'].toString());
    if (code == 1 && mounted) {
      dataList.removeAt(index);
      setState(() {});
    }
  }
}
